<!--
 * @Description: In User Settings Edit
 * @Author: your name
 * @Date: 2019-08-07 10:48:43
 * @LastEditTime: 2019-08-15 18:08:32
 * @LastEditors: Please set LastEditors
 -->
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0,maximum-scale=1.0, user-scalable=no">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>抽奖</title>
    <link rel="stylesheet" href="./css/typo.css">
    <link rel="stylesheet" href="./css/GB-canvas-turntable.css">
    <link rel="stylesheet" href="./lottery.css">
</head>
<body>
    <script>
        //Rem
        (function (win, doc) {
            if (!win.addEventListener) return;
            var html = document.documentElement;

            function setFont() {
                var w = html.clientWidth,
                h = html.clientHeight;
                html.style.fontSize = w > h ? w / 1334 * 100 + "px" : w / 750 * 100 + "px";
            }

            setFont();

            setTimeout(function () {
            setFont();
            }, 0);
            doc.addEventListener('DOMContentLoaded', setFont, false);
            win.addEventListener('resize', setFont, false);
            win.addEventListener('load', setFont, false);
        })(window, document);
    </script>
    <section class="m-head">
        <p class="u-name">幸运大转盘</p>
        <p>百分百有礼</p>
    </section>
    <section class="m-dial">
        <section class="turntable-wrap testWrap">
            <div class="light" id="turntable_light"></div>
            <section id="turntable" class="gb-turntable">
                <div class="gb-turntable-container">
                <canvas class="gb-turntable-canvas" width="300" height="300px">抱歉！浏览器不支持。</canvas>
                </div>
        
                <a class="gb-turntable-btn" href="javascript:;">
                <img style="width: 100%;height: 100%;" src="./images/1565145315.png" alt="" srcset="">
                </a>
            </section>
        </section>
    </section>
    <section class="m-link">
        <p>每次抽奖消耗<span class="fBold" id="inter_use">100</span>积分</p>
        <p>免费抽奖,剩余<span class="_num" id="prize_num">10</span>次
        </p>
    </section>
    <section class="m-notice" id="notice_record">
    </section>
    <section class="m-prizePop none" id="prize_pop"
        onclick="handlePrizePop()"
    >
        <div class="u-wrap"
            id="pirceWrap"
        >
            <img 
                class="_img"
                src="./images/adborn.png" alt="">
            <div class="_title">
                恭喜您中奖
            </div>
            <div class="_spec">
                
            </div>
            <div class="_btn">
                查看奖品
            </div>
        </div>
    </section>
    <script type="text/javascript" src="https://res.wx.qq.com/open/js/jweixin-1.3.2.js"></script>
    <script src="js/GB-canvas-turntable.js"></script>
    <script>    
        var user_token = "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJpc3MiOiJPbmVCYXNlIEpXVCIsImlhdCI6MTU2NTg1NjUwNiwiZXhwIjoxNTc0NDk2NTA2LCJhdWQiOiJPbmVCYXNlIiwic3ViIjoiT25lQmFzZSIsImRhdGEiOnsiaWQiOjg5LCJuaWNrbmFtZSI6InRlc3QiLCJwaG90byI6Imh0dHA6XC9cL2FwaS44eWkyMzQ1LmNvbVwvbGF3c29uXC9oZWFkaW1nXC8yMDE5MDgxNVwvNDFjNzU3OGU3ZDVkOGFjYTQxNGZhOTNkZTAwY2E1MjkuanBnIiwiYWdlIjowLCJzZXgiOjEsInVuaW9uaWQiOiJvQWlGZTFaYXZWa0JEY3BLQm9SRHExcVJBQko4IiwiY3JlYXRlX3RpbWUiOiIyMDE4LTA3LTIzIDA5OjI4OjE2In19.gY-LF2JvlzTWccMBzWcYkSMJpZdTcyJo-IiqeAM22Ag";
        var priceNum = 0;
        const prizeNumDom = document.getElementById('prize_num');
        const interUseDom = document.getElementById('inter_use');
        const noticeDom = document.getElementById('notice_record');
        const prizePopDom = document.getElementById('prize_pop');
        const pirceWrapDom = document.getElementById('pirceWrap');
        const navTickeDom = pirceWrapDom.getElementsByClassName('_btn')[0];
        pirceWrapDom.onclick = function (e) {
            e.stopPropagation();
        }
        navTickeDom.onclick = function () {
            wx.miniProgram.switchTab({url: '/pages/tarBar/coupons/index'})
        }
        init();
        /*
        * 修改免费抽奖次数
        * */
        function updatePriceNum(num) {
            priceNum = num;
            prizeNumDom.innerHTML = num;
        }
        /*
        * 创建抽奖记录
        * */
        function createPirzeRecord (prize_record) {
            prize_record = prize_record.slice(0,2);
            let html = '';
            prize_record.map((record)=>{
                html   += `
                    <div class="flexItemCenter _wrap">
                        <img
                            class="_adborn"
                            src="./images/notice_ico.png" alt=""
                        >   
                        <p class="mr40">${record.username}</p>
                        <p>${record.str}</p>
                    </div>
                `;
            });
            noticeDom.innerHTML = html;
        }
        // 获取礼品列表/页面相关参数
        function getPriceList () {
            /*请求参数*/
            var paramObj = {
                httpUrl : 'http://192.168.2.41:20002/api/lawson/get_prize_list',
                type : 'post',
                data : {
                }
            }
            /*请求调用*/
            httpRequest(paramObj,function(respondDada) {
                //这里编写成功的回调函数
                console.log(JSON.parse(respondDada));
                respondDada = JSON.parse(respondDada);
                let { list,times,prize_points,prize_record } = respondDada;
                interUseDom.innerHTML=prize_points;
                updatePriceNum(times);
                createPirzeRecord(prize_record);
                createTurntableFn(list);
            },function() {
                alert('网络错误')
            });
        }
        function handlePrizePop () {
            prizePopDom.classList.add('none');
        }
        function handleGetPrize (data) {
            prizePopDom.classList.remove('none');
            prizePopDom.getElementsByClassName('_spec')[0].innerHTML= '成功抽到' + data;
        }
        // 异步抽奖
        function getWinPriceId (resolve,reject) {
            /*请求参数*/
            var paramObj = {
                httpUrl : 'http://192.168.2.41:20002/api/lawson/random_prize',
                type : 'post',
                data : {
                }
            }
            /*请求调用*/
            httpRequest(paramObj,function(respondDada) {
                //这里编写成功的回调函数
                console.log(JSON.parse(respondDada));
                respondDada = JSON.parse(respondDada);
                let { code,msg,data } =  respondDada;
                if (Number(code) === 0) {
                    if (priceNum) {
                        updatePriceNum(priceNum - 1);
                    }
                    resolve({
                        priceId: data.frontend_index,
                        chances: 1
                    });
                }else{
                    alert(msg);
                }
            },function() {
                reject({data:0})
            });
        }
        // 创建转盘
        function createTurntableFn (turntableArr) {
            gbTurntable.init({
                id: 'turntable',
                config: function (callback) {
                    callback && callback(turntableArr)
                },
                getPrize: function (callback) {
                    let p1 = new Promise(getWinPriceId);
                    p1.then((res)=>{
                        // 参数1 中奖索引  
                        // 参数2 可抽奖次数
                        callback && callback([res.priceId, res.chances]);
                    })
                },
                gotBack: function (data) {
                    handleGetPrize(data);
                }
            });
        }
        // http请求
        function httpRequest(paramObj,fun,errFun) {
            var xmlhttp = null;
            /*创建XMLHttpRequest对象，
            *老版本的 Internet Explorer（IE5 和 IE6）使用 ActiveX 对象：new ActiveXObject("Microsoft.XMLHTTP")
            * */
            if(window.XMLHttpRequest) {
                xmlhttp = new XMLHttpRequest();
            }else if(window.ActiveXObject) {
                xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
            }
            /*判断是否支持请求*/
            if(xmlhttp == null) {
                alert('你的浏览器不支持XMLHttp');
                return;
            }
            /*请求方式，并且转换为大写*/
            var httpType = (paramObj.type || 'GET').toUpperCase();
            /*数据类型*/
            var dataType = paramObj.dataType || 'json';
            /*请求接口*/
            var httpUrl = paramObj.httpUrl || '';
            /*是否异步请求*/
            var async = paramObj.async || true;
            /*请求参数--post请求参数格式为：foo=bar&lorem=ipsum*/
            var paramData = paramObj.data || [];
            var requestData = '';
            for(var name in paramData) {
                requestData += name + '='+ paramData[name] + '&';
            }
            requestData = requestData == '' ? '' : requestData.substring(0,requestData.length - 1);
            console.log(requestData)
            
            /*请求接收*/
            xmlhttp.onreadystatechange = function() {
            if(xmlhttp.readyState == 4 && xmlhttp.status == 200) {
            /*成功回调函数*/
            fun(xmlhttp.responseText);
            }else{
                /*失败回调函数*/
                errFun;
            }
            }			
            /*接口连接，先判断连接类型是post还是get*/
            if(httpType == 'GET') {
                xmlhttp.open("GET",httpUrl,async);
                xmlhttp.setRequestHeader("Global-User-Token", user_token); 
                xmlhttp.send(null);
            }else if(httpType == 'POST'){
                xmlhttp.open("POST",httpUrl,async);
                xmlhttp.setRequestHeader("Global-User-Token", user_token); 
                //发送合适的请求头信息
                xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded"); 
                xmlhttp.send(requestData); 
            }
        }
        // 创建装饰灯
        function createLight () {
            let lightDom =  document.querySelector('#turntable_light');
            let lightNum =18;
            // 初始化灯
            let lightFragment = document.createDocumentFragment();
            for (let i = 0; i < lightNum; i++) {
                let lightItem = document.createElement('span');
                let deg = (360 / lightNum) * i
                lightItem.style.transform = `rotate(${deg}deg)`;
                lightFragment.appendChild(lightItem);
            }
            lightDom.appendChild(lightFragment);
        }
        function getUserToken () {
            let token = getQueryString('token');
            if (token) {
                user_token = token;
            }else{
                alert('出错了');
            }
        }
        // 初始化
        function init () {
            getUserToken();
            getPriceList();
            createLight();
        }

        function getQueryString(name) {  
            var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)", "i");  
            var r = window.location.search.substr(1).match(reg);  
            if (r != null) return decodeURI(r[2]);
            return null;  
        }
    </script>
</body>
</html>